package org.ISCS.utils;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.core.io.ResourceLoader;

import java.io.*;
import java.util.function.Consumer;

@Component
public class MavenPackager {

    private final ResourceLoader resourceLoader;

    public MavenPackager() {
        this.resourceLoader = new DefaultResourceLoader();
    }
    public void packageService(String projectPath, String serviceName) {
        File projectDirectory = new File(projectPath, serviceName);
        System.out.println(projectDirectory.getAbsolutePath());
        File pomFile = new File(projectDirectory, "pom.xml");

        if (pomFile.exists() && !pomFile.isDirectory()) {
            // 执行 Maven 打包
            try {
                ProcessBuilder processBuilder = new ProcessBuilder();
                processBuilder.command("mvn", "clean", "package");
                processBuilder.directory(projectDirectory);
                Process process = processBuilder.start();

                // Separate threads to handle output stream and error stream
                new StreamGobbler(process.getInputStream(), System.out::println).start();
                new StreamGobbler(process.getErrorStream(), System.err::println).start();

                int exitCode = process.waitFor();
                if (exitCode != 0) {
                    throw new RuntimeException("Maven command failed with exit code: " + exitCode);
                }
                System.out.println("打包成功");
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("pom.xml does not exist");
        }
    }
    private static class StreamGobbler extends Thread {
        private InputStream inputStream;
        private Consumer<String> consumer;

        public StreamGobbler(InputStream inputStream, Consumer<String> consumer) {
            this.inputStream = inputStream;
            this.consumer = consumer;
        }

        @Override
        public void run() {
            new BufferedReader(new InputStreamReader(inputStream)).lines()
                    .forEach(consumer);
        }
    }
}